<?php

namespace app\modules\v1\controllers;

use app\modules\v1\components\BaseController;
use common\models\db\User;
use Yii;

/**
 * 小程序用户相关接口
 */
class UserController extends BaseController
{
    /**
     * 用户登录/注册 API
     * @return void
     */
    public function actionLogin()
    {
        $code = $this->getPostData('code', '');
        $userInfo = $this->getPostData('userInfo', []);
        
        if (empty($code)) {
            $this->error('微信登录code不能为空', 400);
        }
        
        // 调用微信接口获取openid
        $appId = Yii::$app->params['wechat']['appId'];
        $appSecret = Yii::$app->params['wechat']['appSecret'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
        
        $response = file_get_contents($url);
        $result = json_decode($response, true);
        
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $this->error('微信登录失败: ' . $result['errmsg'], 1002);
        }
        
        $openId = $result['openid'];
        
        // 查找或创建用户
        $user = User::findOne(['open_id' => $openId]);
        if (!$user) {
            $user = new User();
            $user->open_id = $openId;
            $user->created_at = date('Y-m-d H:i:s');
        }
        
        // 更新用户信息
        if (!empty($userInfo)) {
            $user->nick_name = isset($userInfo['nickName']) ? $userInfo['nickName'] : '';
            $user->avatar_url = isset($userInfo['avatarUrl']) ? $userInfo['avatarUrl'] : '';
        }
        
        $user->updated_at = date('Y-m-d H:i:s');
        
        if (!$user->save()) {
            $this->error('保存用户信息失败', 1002);
        }
        
        // 生成token
        $token = $this->generateToken($user->id, $openId);
        
        $data = [
            'userId' => $user->id,
            'openId' => $openId,
            'nickName' => $user->nick_name,
            'avatarUrl' => $user->avatar_url,
            'token' => $token
        ];
        
        $this->success($data, '登录成功');
    }
    
    /**
     * 获取用户信息 API
     * @return void
     */
    public function actionInfo()
    {
        $user = $this->user;
        
        $data = [
            'userId' => $user->id,
            'nickName' => $user->nick_name,
            'avatarUrl' => $user->avatar_url
        ];
        
        $this->success($data, '获取成功');
    }
    
    /**
     * 更新用户信息 API
     * @return void
     */
    public function actionUpdate()
    {
        $user = $this->user;
        
        $nickName = $this->getPostData('nickName', '');
        $avatarUrl = $this->getPostData('avatarUrl', '');
        
        if (!empty($nickName)) {
            $user->nick_name = $nickName;
        }
        
        if (!empty($avatarUrl)) {
            $user->avatar_url = $avatarUrl;
        }
        
        $user->updated_at = date('Y-m-d H:i:s');
        
        if (!$user->save()) {
            $this->error('更新用户信息失败', 500);
        }
        
        $data = [
            'userId' => $user->id,
            'nickName' => $user->nick_name,
            'avatarUrl' => $user->avatar_url
        ];
        
        $this->success($data, '更新成功');
    }
    
    /**
     * 生成用户认证token
     * @param int $userId 用户ID
     * @param string $openId 微信openId
     * @return string
     */
    private function generateToken($userId, $openId)
    {
        $timestamp = time();
        $tokenData = [
            'userId' => $userId,
            'openId' => $openId,
            'timestamp' => $timestamp
        ];
        
        // 生成token数据部分
        $tokenPart = base64_encode(json_encode($tokenData));
        
        // 生成签名
        $signature = md5($userId . $openId . $timestamp . Yii::$app->params['tokenSecret']);
        
        // 组合token
        return $tokenPart . '.' . $signature;
    }
} 